<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/20
 * Time: 17:26
 */

namespace app\push\controller;

use \app\check\controller\Check;
use app\common\model\User;
use JPush\Client as JPushClient;

/**
 * @title 推送绑定
 * @desc 用户登录或者开启通知权限后进行，注册id绑定
 * @url
 * @version 1.1.2
 * Class Bind
 * @readme /doc/md/push/base.md
 */
class Bind extends Check
{
    protected $restActionList = ['save'];

    /**
     * @title 推送说明
     * @method
     * @desc
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作');
        }
        return show(200, '成功');
    }

    /**
     * @title
     * @method GET
     * @desc
     * @return array
     */
    public function read()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作');
        }
        return show(200, '成功', []);
    }

    /**
     * @title 推送设备绑定
     * @method POST
     * @desc /push/bind
     * @readme /doc/md/push/save.md
     * @throws \app\common\lib\exception\ApiException
     */
    public function save()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作');
        }
        // 用户id
        $uid = $this->user['id'];
        // 注册id
        $regid = input('post.regid/s');


        if ($uid && $regid)
        {
            (new User())->updateRegid(['uid' => $uid, 'regid' => $regid]);
        }

        return show(200, '提交成功');
    }

    /**
     * @title
     * @method PUT
     * @desc
     * @return array
     */
    public function update()
    {
        if (!request()->isPut())
        {
            return show(config('code.error'), '未知操作');
        }
        return show(200, '更新成功');
    }

    /**
     * @title
     * @method DELETE
     * @desc
     * @return array
     */
    public function delete()
    {
        if (!request()->isDelete())
        {
            return show(config('code.error'), '未知操作');
        }
        return show(200, '删除成功');
    }

    /**
     * 参数规则
     * @name 字段名称
     * @type 类型
     * @require 是否必须
     * @default 默认值
     * @desc 说明
     * @range 范围
     * @return array
     */
    public static function getRules()
    {
        $rules = [
            'index' => [

            ],
            'read' => [
                'id' => ['name' => 'id', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '档案id', 'range' => '',],
            ],
            'save' => [
                'access_token' => ['name' => 'access_token', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '接口访问凭证', 'range' => '32位',],
                'ucid' => ['name' => 'ucid', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '用户ucid', 'range' => '32位',],
                'regid' => ['name' => 'regid', 'type' => 'string', 'require' => 'true', 'default' => '无', 'desc' => '推送客户端注册id', 'range' => '',],
            ],
            'update' => [
                'id' => ['name' => 'id', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '档案id', 'range' => '',],

            ],
            'delete' => [
                'id' => ['name' => 'id', 'type' => 'int', 'require' => 'true', 'default' => '无', 'desc' => '档案id', 'range' => '',],
            ],
        ];
        return $rules;
    }


    /**
     * 推送所有人
     */
    public function push_all()
    {
        $alert = '您提交的校准生辰已经完成了，赶快去查看吧！';
        $msg = [
            'extras' => [
                'version' => '1.2.0',
                'target' => 'link',
                'address' => 'http://www.goddessxzns.com',
            ]
        ];

        $result = $this->notifyAllUser($alert, $msg, config('jpush.app_key'), config('jpush.master_secret'));
        halt($result);
    }

    /**
     * 推送给特定用户
     * @param string $alert
     * @param string $regid
     * @param string $action
     * @param int $id
     */
    public function push_special($alert = '您提交的校准生辰已经完成了，点击查看校正结果！', $regid = '190e35f7e015dc4c09a', $action = 'rectification_details', $id = 0)
    {
        $params = array(
            'extras' => [
                'target' => 'local',
                'link' => $action . '?id=' . $id,
            ]
        );
//        $regid = ['190e35f7e015dc4c09a', '101d85590916c046969'];// android , ios

        $result = $this->sendNotifySpecial($regid, $alert, $params, config('jpush.app_key'), config('jpush.master_secret'));
        halt($result);
    }

    /**
     * 向所有设备推送消息-广播
     * @param $alert
     * @param $message
     * @param $app_key
     * @param $master_secret
     * @return mixed
     */
    private function notifyAllUser($alert, $message, $app_key, $master_secret)
    {
        $client = new JPushClient($app_key, $master_secret, null);

        $result = $client->push()
            ->addAllAudience() // 推送所有
            ->setPlatform('all')
            ->iosNotification($alert, $message)
            ->androidNotification($alert, $message)
            ->send();

        return $this->json_array($result);
    }

    /**
     * 将数据先转换成json,然后转成array
     * @param $result
     * @return mixed
     */
    private function json_array($result)
    {
        $result_json = json_encode($result);
        return json_decode($result_json, true);
    }

    /**
     * 向特定设备推送消息
     * @param $regid string 设备注册id
     * @param $alert
     * @param $param
     * @param $app_key
     * @param $master_secret
     * @return mixed
     */
    private function sendNotifySpecial($regid, $alert, $param, $app_key, $master_secret)
    {
        $client = new JPushClient($app_key, $master_secret, null);

        $androidParam = [
            'builder_id' => 0,
            'style' => 0,
            'priority' => 1,
            'extras' => $param['extras'],
        ];

        $iosParam = [
            'builder_id' => 0,
            'style' => 0,
            'priority' => 1,
            'sound' => 'default',
            'extras' => $param['extras'],
        ];


        $result = $client->push()
            ->setPlatform('all')
//            ->message($alert) // 应用内消息
            ->addRegistrationId($regid)
            ->iosNotification($alert, $iosParam)
            ->androidNotification($alert, $androidParam)
            ->send();
        return $this->json_array($result);
    }
}
